from django.shortcuts import render, redirect
from .forms import LoginForm, RegForm,ChangeNicknameForm,BindEmailForm,ChangePasswordForm,ForGotPasswordForm
from django.contrib import auth
from django.contrib.auth.models import User
from django.urls import reverse
from django.http import JsonResponse
from .models import Profile
from django.core.mail import send_mail
import string
import random
import time
# Create your views here.

# 登录
def login(request):
    ##web form使用
    '''
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(request, username=username, password=password)
    referer = request.META.get('HTTP_REFERER',reverse('home')) #reverse反向解析
    if user is not None:
        auth.login(request, user)
        return redirect(referer)#重定向
    else:
        return render(request, 'error.html', {'message': '用户名密码不正确','redirect_to':referer})
    '''

    ##django form 模块
    if request.method == 'POST':
        login_form = LoginForm(request.POST)
        if login_form.is_valid():  ##认证通过
            user = login_form.cleaned_data['user']  ##在forms里面获取验证
            auth.login(request, user)
            ##from来自详情页 ?from=
            return redirect(request.GET.get('from', reverse('home')))  # 重定向

    else:
        login_form = LoginForm()
    context = {}
    context['login_form'] = login_form
    return render(request, 'user/login.html', context)

def login_for_medal(request):
    data = {}
    login_form = LoginForm(request.POST)
    if login_form.is_valid():  ##认证通过
        user = login_form.cleaned_data['user']  ##在forms里面获取验证
        auth.login(request, user)

        data['status'] = 'SUCCESS'
    else:
        data['status'] = 'ERROR'
    return JsonResponse(data)

def logout(request):
    auth.logout(request)

    ##from来自详情页 ?from=
    return redirect(request.GET.get('from', reverse('home')))  # 重定向


def register(request):
    if request.method == 'POST':
        reg_form = RegForm(request.POST,request=request)
        if reg_form.is_valid():  ##认证通过
            username = reg_form.cleaned_data['username']
            email = reg_form.cleaned_data['email']
            password = reg_form.cleaned_data['password']
            # 创建用户
            user = User.objects.create_user(username, email, password)
            user.save()
            #清楚session
            del request.session['register_code']
            # 登录用户
            user = auth.authenticate(username=username, password=password)
            auth.login(request, user)
            return redirect(request.GET.get('from', reverse('home')))  # 跳转


    else:
        reg_form = RegForm()
    context = {}
    context['reg_form'] = reg_form
    return render(request, 'user/register.html', context)

#用户资料
def user_info(request):
    context = {}

    return render(request,'user/user_info.html',context)


#修改昵称
def change_nickname(request):
    redirect_to =  request.GET.get('from', reverse('home'))

    if request.method == 'POST':
        form = ChangeNicknameForm(request.POST,user=request.user)
        if form.is_valid():
            nickname_new = form.cleaned_data['nickname_new']
            profile,created = Profile.objects.get_or_create(user=request.user)
            profile.nickname = nickname_new
            profile.save()
            return redirect(redirect_to)

    else:
        form =ChangeNicknameForm()

    context = {}
    context['page_title'] = '修改昵称'
    context['form_title'] = '修改昵称'
    context['submit_text'] = '修改'
    context['form'] = form
    context['return_back_url'] = redirect_to
    return render(request,'form.html',context)

#邮箱
def bind_email(request):
    redirect_to = request.GET.get('from', reverse('home'))

    if request.method == 'POST':
        form = BindEmailForm(request.POST, request=request)
        if form.is_valid():
            email = form.cleaned_data['email']
            request.user.email = email
            request.user.save()
            # 清楚session
            del request.session['bind_email_code']
            return redirect(redirect_to)

    else:
        form = BindEmailForm()

    context = {}
    context['page_title'] = '绑定邮箱'
    context['form_title'] = '绑定邮箱'
    context['submit_text'] = '绑定'
    context['form'] = form
    context['return_back_url'] = redirect_to
    return render(request, 'user/bind_email.html', context)

#发送验证码
def send_verification_code(request):
    data = {}
    email  = request.GET.get('email','')
    send_for = request.GET.get('send_for','')
    if email != '':
        #生成验证码
        code = ''.join(random.sample(string.ascii_letters + string.digits,4))

        now = int(time.time())
        send_code_time = request.session.get('send_code_time',0)
        if now - send_code_time < 30:
            data['status'] = 'ERROR'
        else:
            request.session[send_for] = code
            request.session['send_code_time'] = now
            #发送邮件
            send_mail(
                '绑定邮箱',
                '验证码: %s' % code,
                '1733164775@qq.com',
                [email],
                fail_silently=False,
            )
            data['status'] = 'SUCCESS'
    else:
        data['status'] = 'ERROR'
    return JsonResponse(data)


#修改密码
def change_password(request):
    redirect_to = reverse('home')
    if request.method == 'POST':
        form = ChangePasswordForm(request.POST, user=request.user)
        if form.is_valid():
            user = request.user
            old_password = form.cleaned_data['old_password']
            new_password = form.cleaned_data['new_password']
            user.set_password(new_password)
            user.save()
            pass
            #修改成功登出
            auth.logout(request)
            return redirect(redirect_to)

    else:
        form = ChangePasswordForm()

    context = {}
    context['page_title'] = '修改密码'
    context['form_title'] = '修改密码'
    context['submit_text'] = '修改'
    context['form'] = form
    context['return_back_url'] = redirect_to
    return render(request, 'form.html', context)

#
def forgot_password(request):
    redirect_to = reverse('login')

    if request.method == 'POST':
        form = ForGotPasswordForm(request.POST, request=request)
        if form.is_valid():
            email = form.cleaned_data['email']
            new_password = form.cleaned_data['new_password']
            user = User.objects.get(email=email)
            user.set_password(new_password)
            user.save()

            # 清楚session
            del request.session['forgot_password_code']
            return redirect(redirect_to)

    else:
        form = ForGotPasswordForm()

    context = {}
    context['page_title'] = '重置密码'
    context['form_title'] = '重置密码'
    context['submit_text'] = '重置'
    context['form'] = form
    context['return_back_url'] = redirect_to
    return render(request, 'user/forgot_password.html', context)


